package cn.zhz.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.zhz.pojo.User;
import cn.zhz.service.user.UserService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController{
	private Logger logger = Logger.getLogger(UserController.class);
	@RequestMapping({"/welcome","/"})
	public String welcome(String username){
		logger.info("welcome, username:" + username);
		return "index";
	}

	private ArrayList<User> userList = new ArrayList<User>();
	private ArrayList<User> queryUserList = new ArrayList<User>();
	public UserController(){
		try{
			userList.add(new User(1,"test001","测试用户001","1111111",1,new SimpleDateFormat("yyyy-MM-dd").parse("1986-12-10"),"13566669998","北京市朝阳区北苑",1,1,new Date(),1,new Date()));
			userList.add(new User(2,"zhaoyan","赵燕","2222222",1,new SimpleDateFormat("yyyy-MM-dd").parse("1984-11-10"),"18678786545","北京市海淀区成府路",1,1,new Date(),1,new Date()));
			userList.add(new User(3,"test003","测试用户003","3333333",1,new SimpleDateFormat("yyyy-MM-dd").parse("1980-11-11"),"13121334531","北京市通州北苑",1,1,new Date(),1,new Date()));
			userList.add(new User(4,"wanglin","王林","4444444",1,new SimpleDateFormat("yyyy-MM-dd").parse("1989-09-10"),"18965652364","北京市学院路",1,1,new Date(),1,new Date()));
			userList.add(new User(5,"zhaojing","赵静","5555555",1,new SimpleDateFormat("yyyy-MM-dd").parse("1981-08-01"),"13054784445","北京市广安门",1,1,new Date(),1,new Date()));
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	//没有查询条件的情况下，获取userList(公共查询)
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String list(Model model){
		logger.info("无查询条件下，获取userList(公共查询)==== userList");
		model.addAttribute("queryUserList",userList);
		return "user/userlist";
	}
	//增加查询条件：userName
	@RequestMapping(value="/list",method=RequestMethod.POST)
	public String list(@RequestParam(value="userName",required=false) String userName,Model model){
		logger.info("查询条件：userName: " + userName +", 获取userList==== ");
		if(userName != null && !userName.equals("")){
			for(User user:userList){
				if(user.getUserName().indexOf(userName) != -1){
					queryUserList.add(user);
				}
			}
			model.addAttribute("queryUserList",queryUserList);
		}else{
			model.addAttribute("queryUserList",userList);
		}
		return "user/userlist";
	}

    @Resource
    private UserService userService;

    @RequestMapping(value="/login.html")
    public String login(){
        logger.debug("UserController welcome SMBMS==================");
        return "login";
    }

    @RequestMapping(value="/dologin.html",method=RequestMethod.POST)
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, HttpServletRequest request, HttpSession session){
        logger.debug("doLogin====================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);
        if(null != user){//登录成功
            //页面跳转（frame.jsp）
            return "redirect:/user/main.html";
            //response.sendRedirect("jsp/frame.jsp");
        }else{
            //页面跳转（login.jsp）带出提示信息--转发
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }

    @RequestMapping(value="/exlogin.html",method=RequestMethod.GET)
    public String exLogin(@RequestParam String userCode,@RequestParam String userPassword){
        logger.debug("exLogin====================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);
        if(null == user){//登录失败
            throw new RuntimeException("用户名或者密码不正确！");
        }
        return "redirect:/user/main.html";
    }

    @RequestMapping(value="/userlist.html")
    public String getUserList(Model model,
                              @RequestParam(value="queryname",required=false) String queryUserName,
                              @RequestParam(value="queryUserRole",required=false) String queryUserRole,
                              @RequestParam(value="pageIndex",required=false) String pageIndex){
        logger.info("getUserList ---- > queryUserName: " + queryUserName);
        logger.info("getUserList ---- > queryUserRole: " + queryUserRole);
        logger.info("getUserList ---- > pageIndex: " + pageIndex);
        int _queryUserRole = 0;
        List<User> userList = null;
        //当前页码
        int currentPageNo = 1;
        if(queryUserName == null){
            queryUserName = "";
        }
        if(queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }
        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                return "redirect:/user/syserror.html";
                //response.sendRedirect("syserror.jsp");
            }
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,_queryUserRole);
        //控制首页和尾页
        if(currentPageNo < 1) {
            currentPageNo = 1;
        }
        model.addAttribute("userList", userList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "userlist";
    }

    @RequestMapping(value="/syserror.html")
    public String sysError(){
        return "syserror";
    }
}
